using MongoDB.Driver.Builders;
using NetFluid;
using Sito.model;
using Textile;

namespace Sito.Logic
{
    internal class WikiManager : FluidPage
    {
        [Route("/wiki")]
        public void wiki(string name, bool plain)
        {
            Wiki p = Database.Wiki.FindOne(Query.EQ("Name", name));

            if (plain)
            {
                if (p != null)
                {
                    print(p.Content);
                }
                else
                {
                    ResponseCode = StatusCode.NotFound;
                }
            }
            else
            {
                if (p != null)
                {
                    //display the wiki
                    render("Sito.View.Wiki", p, name);
                }
                else
                {
                    //display the edit page
                    render("Sito.View.Wiki", null, name);
                }
            }
        }

        [Route("/wiki/save")]
        public void save(string name, string content, bool plain)
        {
            Wiki page = Database.Wiki.FindOne(Query.EQ("Name", name));

            if (page == null)
            {
                page = new Wiki
                           {
                               Name = name,
                               Content = content,
                               FormattedContent = TextileFormatter.FormatString(content)
                           };
                Database.Wiki.Save(page);
            }
            else
            {
                page.Content = content;
                page.FormattedContent = TextileFormatter.FormatString(page.Content);
                Database.Wiki.Save(page);
            }


            if (plain)
            {
                print(page.FormattedContent);
            }
            else
            {
                ResponseHeaders.Add("Location", "/wiki?name=" + name.UrlEncode());
                ResponseCode = (StatusCode) 302;
            }
        }
    }
}